
<template>
  <!-- 导航部分 -->
  <el-row>
    <el-col :span="24">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item>项目管理</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
  </el-row>
  <!-- 搜索栏 -->
  <el-row style="margin-top: 10px">
    <el-col :span="24">
      <el-form :model="projectQuery" inline>
        <el-form-item label="项目名称">
          <el-input v-model="projectQuery.projectName"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select placeholder="全部" style="width:100px" v-model="projectQuery.projectStatus">
            <el-option label="全部" :value="0"/>
            <el-option label="草稿状态" :value="1"/>
            <el-option label="发布状态" :value="2"/>
            <el-option label="归档状态" :value="3"/>
            <el-option label="暂停状态" :value="4"/>
            <el-option label="意外状态" :value="5"/>
            <el-option label="删除状态" :value="99"/>
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间">
          <el-date-picker
              v-model="startTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
              v-model="endTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item>
          <el-button @click="loadProjects">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>

  <!-- 工具栏 -->
  <el-row style="margin-top: 10px">
    <el-col :span="24">
      <el-button type="primary" @click="toAdd">新增项目</el-button>
      <el-button type="primary" @click="toRelease">发布项目</el-button>
      <el-button type="primary">编辑项目</el-button>
      <el-button type="primary" @click="toDeletes">删除项目</el-button>
      <el-button type="primary" @click="toFiles">归档项目</el-button>
    </el-col>
  </el-row>
  <!-- 数据表 -->
  <el-row style="margin-top: 10px">
    <el-col :span="24">
      <el-table
          :data="projects"
          border
          stripe ref="projectTable"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="projectId" label="项目编号">
          <template #default="scope">
            <el-link type="success" @click="projectIdList(scope.row.projectId)">{{ scope.row.projectId }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="projectName" label="项目名称"/>
        <el-table-column prop="user.userName" label="项目负责人"/>
        <el-table-column prop="countTasks" label="任务数量"/>
        <el-table-column prop="startTime" label="开始时间"/>
        <el-table-column prop="endTime" label="结束时间"/>

        <el-table-column prop="projectStatus" label="项目状态">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.projectStatus == 1">草稿状态</el-tag>
            <el-tag type="success" v-else-if="scope.row.projectStatus == 2">发布状态</el-tag>
            <el-tag type="success" v-else-if="scope.row.projectStatus == 3">归档状态</el-tag>
            <el-tag type="success" v-else-if="scope.row.projectStatus == 4">暂停状态</el-tag>
            <el-tag type="success" v-else-if="scope.row.projectStatus == 5">意外状态</el-tag>
            <el-tag type="success" v-else-if="scope.row.projectStatus == 6">删除状态</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="330">
          <template #default="scope">
            <el-button-group>
              <template v-if="scope.row.userId == choseUserId">
                <el-button size="small" type="primary" @click="changeProjectById(scope.row.projectId)">编辑</el-button>
                <el-button size="small" type="info" @click="updateFile(scope.row.projectId)">归档</el-button>
                <el-button size="small" type="danger" @click="deleteProject(scope.row.projectId)">删除</el-button>
              </template>
              <el-button size="small" type="primary" @click="toTask(scope.row)">任务</el-button>
              <el-button size="small" type="primary">日历</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
  <!-- 分页栏 -->
  <el-row style="margin-top: 10px">
    <!-- 监听页码的变化事件 -->
    <el-pagination @change="changePage" :total="total" background layout="prev, pager, next"/>
  </el-row>

  <!-- 新增项目的弹窗 -->
  <el-dialog v-model="projectAddWinDialogVisible"
             title="新增项目"
             width="50%"
  >

      <el-form :model="newProject">
        <el-form-item label="项目编号">
          <el-input v-model="newProject.projectId"/>
        </el-form-item>
        <el-form-item label="项目名称">
          <el-input v-model="newProject.projectName"/>
        </el-form-item>

        <el-form-item label="开始时间">
          <el-date-picker
              v-model="newProject.startTime"
              type="date"
              placeholder="Pick a day"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="结束时间">
          <el-date-picker
              v-model="newProject.endTime"
              type="date"
              placeholder="Pick a day"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="项目描述">
          <el-input type="textarea" v-model="newProject.projectDesc"/>


        </el-form-item>
      </el-form>

      <el-button @click="dialogVisible">取消</el-button>
      <el-button type="primary" @click="addProjectSubmit">
        提交
      </el-button>


  </el-dialog>



  <!-- 项目编号详情项目的弹窗 -->
  <el-dialog v-model="projectIdListWinDialogVisible"
             title="项目详情"
             width="50%"
  >

    <el-descriptions column="2">
        <el-descriptions-item label="项目编号">{{projectIdLists.projectId}}</el-descriptions-item>
        <el-descriptions-item label="项目名称">{{projectIdLists.projectName}}</el-descriptions-item>
        <el-descriptions-item label="项目负责人">{{projectIdLists.user.userName}}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{projectIdLists.startTime}}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{projectIdLists.endTime}}</el-descriptions-item>
        <el-descriptions-item label="项目描述">{{projectIdLists.projectDesc}}</el-descriptions-item>

    </el-descriptions>







  </el-dialog>





  <!-- 编辑项目的弹窗 -->
  <el-dialog v-model="projectChangeWinDialogVisible"
             title="编辑项目"
             width="50%"
  >

    <el-form :model="afterChangeProject">
      <el-form-item label="项目编号">
        <el-input v-model="afterChangeProject.projectId"/>
      </el-form-item>
      <el-form-item label="项目名称">
        <el-input v-model="afterChangeProject.projectName"/>
      </el-form-item>

      <el-form-item label="状态">
        <el-radio-group v-model="afterChangeProject.projectStatus">
          <el-radio :value="1" label="草稿状态"/>
          <el-radio :value="2" label="发布状态"/>
          <el-radio :value="3" label="归档状态"/>
          <el-radio :value="4" label="暂停状态"/>
          <el-radio :value="5" label="意外状态"/>
          <el-radio :value="6" label="删除状态"/>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="发布时间">
        <el-input v-model="afterChangeProject.createTime"/>
      </el-form-item>

      <el-form-item label="开始时间">
        <el-date-picker
            v-model="newProject.startTime"
            type="date"
            placeholder="Pick a day"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="结束时间">
        <el-date-picker
            v-model="newProject.endTime"
            type="date"
            placeholder="Pick a day"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>


    </el-form>

    <el-button @click="changeDialogVisible">取消</el-button>
    <el-button type="primary" @click="changeProjectSubmit">
      提交
    </el-button>


  </el-dialog>


</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import {onBeforeUnmount, onMounted, ref, shallowRef} from "vue";
import {ElMessageBox} from "element-plus";
import {Editor,Toolbar} from "@wangeditor/editor-for-vue";
// 导入axios
import axios  from "axios";
import  {useRouter} from "vue-router";
import homeRequest from "@/api/home.js";
import projectRequest from "@/api/projects.js";
import {ElMessage} from "element-plus";
import taskRequest from "@/api/task.js";
// 封装查询条件
let projectQuery = ref({projectStatus: 0});
// 封装当前的页面
let curPage = ref(1);
// 封装查询的结果集合
let projects = ref([])
// 封装查询的数据总条数
let total = ref(0);
let router = useRouter();
//封装两个时间范围
let startTimes = ref([]);
let endTimes = ref([]);
//封装要提交的信息
let editProject = ref({});

//新增弹窗标记
let projectAddWinDialogVisible = ref(false);
//项目编号详情弹窗标记
let projectIdListWinDialogVisible = ref(false);

let projectChangeWinDialogVisible = ref(false);
//保存新增数据
let newProject = ref({});

//项目编号详情数据存储
let projectIdLists = ref({user:{}})

//当前选择登录的userid保存
let choseUserId = ref()

//富文本编辑器相关属性
//编辑器实例，必须用shallowRef
const  editorRef = shallowRef();
//内容HTML,
const valueHtml = ref();
//工具栏
const toolbarConfig = {}

const editorConfig = { placeholder: '请输入内容...' }

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}



//任务列表
let tasks = ref([]);
let project = ref({});// 不需要申明为响应式对
//加载子任务
function loadChildrenTask(task,node,resole){
  console.log(task)
  taskRequest.loadTaskByProjectId(project.value.projectId,task.taskId,res=>{
    resole(res.data);
  })
}


//加载任务列表
function loadTasks(parentId){

  taskRequest.loadTaskByProjectId(project.value.projectId,parentId,res=>{

    tasks.value = res.data;
  })
}


function loadProject(projectId){
  console.log(projectId)
  projectRequest.selectProjectByIdList(projectId, res=>{
    project.value = res.data;
    loadTasks(0);
  })
}


















//跳转到任务
function toTask(project){
    router.push("/home/task/" + project.projectId)
}



//保存前端多选的数据
let projectTable = ref(null);

//批量发布点击事件
function toRelease(){
  let selectedRows = projectTable.value.getSelectionRows();
  console.log(projectTable)
  if (selectedRows.length == 0){
    ElMessage({
      type:"warning",
      message:"你没有选中任何数据"
    });
    return;
  }
  ElMessageBox.confirm(
      '您确定要将选中的项目发布吗？',
      '提示',
      {
        confirmButtonText: '是的',
        cancelButtonText: '点错了',
        type: 'warning',
      }
  ).then(() => {
    let noCurUserProjectNames = [];
    let projectIds = [];
    selectedRows.forEach(row=>{
      if(row.userId != choseUserId.value){
        noCurUserProjectNames.push(row.projectName);
      }
      projectIds.push(row.projectId);
    })
    if(noCurUserProjectNames.length > 0){
      ElMessage({
        type:"warning",
        message:"您选中的项目中，有以下项目[" + noCurUserProjectNames.join(",") + "]并非您管理的，你没有发布权限"
      });
      return;
    }
    console.log(projectIds);
    projectRequest.releases(projectIds,res=>{
      console.log(res);
      if(res.code == 200){
        ElMessage({
          type:"success",
          message:"成功发布[" + res.data + "]条数据"
        })
        loadProjects();
      }else{
        ElMessage({
          type:"warning",
          message:"发布失败"
        })
      }
    });
  }).catch(()=>{});
}






//批量归档点击事件
function toFiles(){
  let selectedRows = projectTable.value.getSelectionRows();
  console.log(selectedRows)
  if (selectedRows.length == 0){
    ElMessage({
      type:"warning",
      message:"你没有选中任何数据"
    });
    return;
  }
  ElMessageBox.confirm(
      '您确定要将选中的项目归档吗？',
      '提示',
      {
        confirmButtonText: '是的',
        cancelButtonText: '点错了',
        type: 'warning',
      }
  ).then(() => {
    let noCurUserProjectNames = [];
    let projectIds = [];
    selectedRows.forEach(row=>{
      if(row.userId != choseUserId.value){
        noCurUserProjectNames.push(row.projectName);
      }
      projectIds.push(row.projectId);
    })
    if(noCurUserProjectNames.length > 0){
      ElMessage({
        type:"warning",
        message:"您选中的项目中，有以下项目[" + noCurUserProjectNames.join(",") + "]并非您管理的，你没有发布权限"
      });
      return;
    }
    console.log(projectIds);
    projectRequest.files(projectIds,res=>{
      console.log(res);
      if(res.code == 200){
        ElMessage({
          type:"success",
          message:"成功归档[" + res.data + "]条数据"
        })
        loadProjects();
      }else{
        ElMessage({
          type:"warning",
          message:"归档失败"
        })
      }
    });
  }).catch(()=>{});
}






//批量删除

function toDeletes(){
  let selectedRows = projectTable.value.getSelectionRows();
  console.log(projectTable.value.getSelectionRows())
  if (selectedRows.length == 0){
    ElMessage({
      type:"warning",
      message:"你没有选中任何数据"
    });
    return;
  }
  ElMessageBox.confirm(
      '您确定要将选中的项目删除吗？',
      '提示',
      {
        confirmButtonText: '是的',
        cancelButtonText: '点错了',
        type: 'warning',
      }
  ).then(() => {
    let noCurUserProjectNames = [];
    let projectIds = [];
    selectedRows.forEach(row=>{
      if(row.userId != choseUserId.value){
        noCurUserProjectNames.push(row.projectName);
      }
      projectIds.push(row.projectId);
    })
    if(noCurUserProjectNames.length > 0){
      ElMessage({
        type:"warning",
        message:"您选中的项目中，有以下项目[" + noCurUserProjectNames.join(",") + "]并非您管理的，你没有发布权限"
      });
      return;
    }
    console.log(projectIds);
    projectRequest.deletes(projectIds,res=>{
      console.log(res);
      if(res.code == 200){
        ElMessage({
          type:"success",
          message:"成功删除[" + res.data + "]条数据"
        })
        loadProjects();
      }else{
        ElMessage({
          type:"warning",
          message:"删除失败"
        })
      }
    });
  }).catch(()=>{});
}







//行归档
function updateFile(projectId){
  projectRequest.updateFile(projectId,res=>{
    if (res.code == 200) {
      console.log(res)
      ElMessage({
        type: "success",
        message: "归档成功"
      });
      // 刷新表格
      loadProjects();
    } else {
      ElMessage({
        type: "error",
        message: "归档失败"
      });
    }
  })
}



//行删除点击事件
function deleteProject(projectId){
  projectRequest.deleteProject(projectId,res=>{
    if (res.code == 200) {
      console.log(res)
      ElMessage({
        type: "success",
        message: "删除成功"
      });
      // 刷新表格
      loadProjects();
    } else {
      ElMessage({
        type: "error",
        message: "删除失败"
      });
    }
  })
}







//保存要编辑的数据
let afterChangeProject = ref([]);
//编辑弹窗显示
function changeProjectById(projectId){
  projectRequest.selectProjectByIdList(projectId,res=>{
    console.log(res)
    afterChangeProject.value = res.data;
    console.log(afterChangeProject)
  })
  projectChangeWinDialogVisible.value = true;
}

//编辑弹窗取消
function changeDialogVisible(){
  projectChangeWinDialogVisible.value = false;
}



//编辑弹窗提交
function changeProjectSubmit(){
  console.log(afterChangeProject)
  projectRequest.updateProjectById(afterChangeProject.value ,res=>{
    if (res.code == 200) {
      console.log(res)
      ElMessage({
        type: "success",
        message: "编辑成功"
      });
      // 关闭窗体
      changeDialogVisible();
      // 刷新表格
      loadProjects();
    } else {
      ElMessage({
        type: "error",
        message: "编辑失败"
      });
    }

  })
}




// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

//项目编号详情弹窗点击事件
function projectIdList(projectId){
  console.log(projectId)

  loadProject(projectId);

  projectIdListWinDialogVisible.value = true;
  projectRequest.selectProjectByIdList(projectId,res=>{
    console.log(res)
    projectIdLists.value = res.data;
    console.log(projectIdLists)
  })
}




//提交
function addProjectSubmit(){


  newProject.value.userId = choseUserId.value;

  projectRequest.saveProject(newProject.value,res => {
    console.log(res)
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "新增成功"
      });
      // 关闭窗体
      dialogVisible();
      // 刷新表格
      loadProjects();
    } else {
      ElMessage({
        type: "error",
        message: "新增失败"
      });
    }
  });
}



//新增
function toAdd(){
  projectAddWinDialogVisible.value = true;
}

//取消
function dialogVisible(){
  projectAddWinDialogVisible.value = false;
}

function loadProjects(){
  //处理查询条件，处理时间范围
  if (startTimes.value[0]) {
    projectQuery.value.startTimeBegin = startTimes.value[0];
  }
  if (startTimes.value[1]) {
    projectQuery.value.startTimeEnd = startTimes.value[1];
  }
  if (endTimes.value[0]) {
    projectQuery.value.endTimeBegin = endTimes.value[0];
  }
  if (endTimes.value[1]) {
    projectQuery.value.endTimeEnd = endTimes.value[1];
  }
  console.log(projectQuery)

  projectRequest.loadProjects(projectQuery.value, curPage.value,10,res =>{
    console.log(res)
    total.value = res.data.total;
    projects.value = res.data.list;
  })
}


function changePage(value){
  curPage.value = value;
  loadProjects();
}



// 在声明周期的onmounted函数中调用loadUsers函数
onMounted(()=>{
  loadProjects();
  choseUserId.value = localStorage.getItem("userId");
})
</script>

<style scoped>

</style>